﻿// extend jQuery with the goFigure method
$.extend({

	// jQuery utility method for retrieving configuration settings from the server
	goFigure: function (options) {

		// set private variables using options if they exist, otherwise defaults
		var _serviceUrl = (options && options.serviceUrl) ? options.serviceUrl : '/gofigure/';
		var _onSuccess = (options && $.isFunction(options.success)) ? options.success : new Function(); // no-op default
		var _onError = (options && $.isFunction(options.error)) ? options.error : new Function();       // no-op default

		this.get = function (settingKey) {

			var onSuccess = _onSuccess;
			var onError = _onError;

			if (arguments.length === 3) {
				if ($.isFunction(arguments[1])) onSuccess = arguments[1];
				if ($.isFunction(arguments[2])) onError = arguments[2];
			}

			// validate key (minimum checks)
			if (settingKey && settingKey.length !== 0) {

				// build url
				var requestUrl = _serviceUrl + settingKey;

				// make request
				$.ajax(requestUrl)
				 .success(function (response) {
				 	// parse the response as JSON and send it to the success callback method
				 	var json = $.parseJSON(response);
				 	onSuccess(json);
				 })
				// delegate error handling to callback method
				 .error(onError);
			}
			else onError('goFigure: Invalid settingKey');

			// return jQuery extension (current instance of goFigure)
			return this;
		};

		// helper method for overriding the success callback method
		this.success = function (onSuccess) {
			// ignore if the caller sent something other than a function
			if ($.isFunction(onSuccess)) _onSuccess = onSuccess;
			else _onSuccess = new Function();

			// return jQuery extension (current instance of goFigure)
			return this;
		};

		// helper method for overriding the error callback method
		this.error = function (onError) {
			// ignore if the caller sent something other than a function
			if ($.isFunction(onError)) _onError = onError;
			else _onError = new Function();

			// return jQuery extension (current instance of goFigure)
			return this;
		};

		// return jQuery extension (new instance of goFigure)
		return this;
	}
});